package cn.glenn._03vehicle.base.exception;

import cn.glenn._03vehicle.base.response.JsonResult;
import cn.glenn._03vehicle.base.response.StatusCode;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ControllerAdvice注解
 * 标识该类为全局异常处理器
 * 当控制器抛出异常时，框架优先检查是否定义了全局异常处理器
 */
@Slf4j
//@Hidden
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException exception){
        log.debug("IllegalArgumentException:{}",exception.getMessage());
        return JsonResult.fail(exception.getMessage());
    }


    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException exception){
        log.debug("RuntimeException:{}",exception.getMessage());
        return JsonResult.fail(exception.getMessage());
    }

    /**
     * 异常处理方法：处理封装类【POJO】参数合法性校验失败的场景
     */
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentValidException(MethodArgumentNotValidException methodArgumentNotValidException){
        log.debug("MethodArgumentNotValidException:{}",methodArgumentNotValidException.getMessage());
        return new JsonResult(StatusCode.VALIDATED_ERROR,methodArgumentNotValidException.getFieldError().getDefaultMessage());
    }


    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException exception){
        String data = exception.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

/*
    @ExceptionHandler
    public JsonResult doHandlerThrowable(Throwable exception){
        log.debug(exception.getMessage());
        return new JsonResult(StatusCode.THROWABLE_EXCEPTION,exception.getMessage());
    }
*/

}
